package com.sdhs.web.controller.contract;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sdhs.common.core.controller.BaseController;
import com.sdhs.common.core.domain.AjaxResult;
import com.sdhs.common.utils.AESUtils;
import com.sdhs.file.utils.ManageListUtil;
import com.sdhs.listmanage.domain.entity.GcManageList;
import com.sdhs.listmanage.service.IGcManageListService;
import com.sdhs.myproject.domain.GcMyprojectInformation;
import com.sdhs.myproject.domain.GcMyprojectProfitMarginMeasurement;
import com.sdhs.myproject.domain.ProjectManageCost;
import com.sdhs.myproject.mapper.GcMyprojectProfitMarginMeasurementMapper;
import com.sdhs.myproject.service.IGcMyprojectInformationService;
import com.sdhs.myproject.service.IProjectManageCostService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.beans.Transient;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * 我的项目主表Controller
 * 整体实现逻辑是，通过ASE解密法务推送过来的数据，判断新增修改和删除，
 *
 * @author add
 * @date 2025-04-04
 */
@RestController
@RequestMapping("/system/myProject")
public class MyprojectController extends BaseController {
    @Autowired
    private IGcMyprojectInformationService gcMyprojectInformationService;

    @Autowired
    private IGcManageListService gcManageListService;

    @Autowired
    private GcMyprojectProfitMarginMeasurementMapper gcMyMeasurementMapper;
    @Autowired
    private IProjectManageCostService projectManageCostService;


    private static final String AES_KEY = "1234567890123456"; // 16字节密钥


    @PostMapping("/addService")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addService(HttpServletRequest req) {
        logger.info("进入接口，请求数据:{} " , req);
        // 1. 获取并解密请求体
        String requestBody = getRequestBody(req);


        try {
            String decryptedData = AESUtils.decrypt(requestBody);
            System.out.println("解密后的数据"+decryptedData+ "解密后的数据");

            // 2. 解析JSON数据
            ObjectMapper objectMapper = new ObjectMapper();
           /* 如果改成对象数组的话需要用GcMyprojectData这个对象*/
            GcMyprojectInformation contracts = objectMapper.readValue(decryptedData, GcMyprojectInformation.class);
            logger.info("请求体数据: {}" , contracts);
            // 3. 处理项目数据
            List<Object> failedItems = processContracts(contracts);

            // 4. 返回处理结果
            return buildResponse(failedItems);

        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(500, "数据处理异常", null);  // 统一返回格式
        }
    }

    /**
     * 处理合同列表并返回失败项
     */
    private List<Object> processContracts(GcMyprojectInformation contracts) {
        List<Object> failedItems = new ArrayList<>();
        try {
            processSingleContract(contracts, failedItems);
        } catch (Exception e) {
            e.printStackTrace();
            addFailedItem(failedItems, contracts);
        }


        return failedItems;
    }

    /**
     * 处理单个项目
     */
    private void processSingleContract(GcMyprojectInformation contract, List<Object> failedItems) {
        insertNewContract(contract, failedItems);
    }

    /**
     * 新增项目
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertNewContract(GcMyprojectInformation contract, List<Object> failedItems) {
        logger.info("进入新增项目");
        contract.setId(null);  // 清空ID让数据库自增
        contract.setProjectStatus("0");
        contract.setIsOrganization("1");
        if (contract.getCreater()!= null && contract.getOrganization()!= null) {
            int result=-1;
            List<GcMyprojectInformation> gcMyprojectInformations = gcMyprojectInformationService.selectMyprojectList(contract);
            if (gcMyprojectInformations.isEmpty()) {
                 result = gcMyprojectInformationService.insertGcMyprojectInformation(contract);
                logger.info(" 返回结果result: {}", result);
            }
            /*查询项目信息中的利润率测算-管理成本上限字段*/
                ProjectManageCost byBusinessIdAndOrganization = projectManageCostService.findByBusinessIdAndOrganization(contract.getBusinessId(), "1");
                    if(byBusinessIdAndOrganization!=null){
                        byBusinessIdAndOrganization.setProjectId(contract.getId());
                        projectManageCostService.updateById(byBusinessIdAndOrganization);
                    }
            logger.info("新增项目信息: {}", contract);
            /*根据商机id和是否主办修改清单*/
             GcManageList gcManageList = new GcManageList();
            gcManageList.setProjectId(contract.getId());
            gcManageList.setIsOrganization("1");
            gcManageList.setBusinessId(contract.getBusinessId());
            List<GcManageList> gcManageLists = gcManageListService.selectGcManageListByBusiness(gcManageList);

            if(!gcManageLists.isEmpty()){
                /*调用王磊的计算方法上面还有一个需要调用*/
                for(GcManageList gcManageList1:gcManageLists){
                    if(gcManageListService.isLeafNode(gcManageList1)){
                        gcManageListService.manageListCompute(gcManageList1);
                        gcManageListService.updateGcManageList(gcManageList1);
                    }

                }
                gcManageListService.updateByBusinessId(gcManageList);
            }
            /*gcManageListService.updateByBusinessId(gcManageList);*/
            if (result < 0) {
                addFailedItem(failedItems, contract);
            }else {
                GcManageList gcManageListNew = new GcManageList();
                gcManageListNew.setProjectId(contract.getId());
                gcManageListNew.setProcurementType("0");
                List<GcManageList> mYgcManageLists = gcManageListService.selectGcManageListList(gcManageListNew);
                ManageListUtil.UpdateMeasurement(contract.getId(), mYgcManageLists);
            }
        }
        // 检查 organizer 和 organizerHead 是否有效（非 null、非空字符串、非纯空格）
        boolean isOrganizerValid = contract.getOrganizer() != null
                && !contract.getOrganizer().trim().isEmpty();
        boolean isOrganizerHeadValid = contract.getOrganizerHead() != null
                && !contract.getOrganizerHead().trim().isEmpty();

        if (isOrganizerValid && isOrganizerHeadValid) {
            GcMyprojectInformation gcMyprojectInformation = new GcMyprojectInformation();
            gcMyprojectInformation.setCreater(contract.getOrganizerHead());
            gcMyprojectInformation.setOrganization(contract.getOrganizer());
            gcMyprojectInformation.setProjectName(contract.getProjectName());
            gcMyprojectInformation.setProjectNumber(contract.getProjectNumber());
            gcMyprojectInformation.setOwnerUnit(contract.getOwnerUnit());
            gcMyprojectInformation.setIsOrganization("0");
            gcMyprojectInformation.setOwnerShipId(contract.getOwnerShipId());
            gcMyprojectInformation.setBusinessId(contract.getBusinessId());
            gcMyprojectInformation.setGcMyprojectProfitMarginMeasurement(contract.getGcMyprojectProfitMarginMeasurement());
            int i = gcMyprojectInformationService.insertGcMyprojectInformation(gcMyprojectInformation);


            /*根据商机id和是否主办修改清单*/
            GcManageList gcManageList = new GcManageList();
            gcManageList.setProjectId(gcMyprojectInformation.getId());
            gcManageList.setIsOrganization("0");
            gcManageList.setBusinessId(contract.getBusinessId());
             List<GcManageList> gcManageLists = gcManageListService.selectGcManageListByBusiness(gcManageList);
            /*查询项目信息中的利润率测算-管理成本上限字段*/
            ProjectManageCost byBusinessIdAndOrganization = projectManageCostService.findByBusinessIdAndOrganization(contract.getBusinessId(), "0");
            if(byBusinessIdAndOrganization!=null){
                byBusinessIdAndOrganization.setProjectId(gcMyprojectInformation.getId());
                projectManageCostService.updateById(byBusinessIdAndOrganization);
            }
             if(!gcManageLists.isEmpty()){
                 /*调用王磊的计算方法上面还有一个需要调用*/
                 for(GcManageList gcManageList1:gcManageLists){
                     if(gcManageListService.isLeafNode(gcManageList1)){
                         gcManageListService.manageListCompute(gcManageList1);

                         gcManageListService.updateGcManageList(gcManageList1);
                     }
                 }
                 gcManageListService.updateByBusinessId(gcManageList);
             }
            /*gcManageListService.updateByBusinessId(gcManageList);*/
            if (i < 0) {
                addFailedItem(failedItems, contract);
            }else {
                GcManageList gcManageListNew = new GcManageList();
                gcManageListNew.setProjectId(gcMyprojectInformation.getId());
                gcManageListNew.setProcurementType("0");
                List<GcManageList> mYgcManageLists = gcManageListService.selectGcManageListList(gcManageListNew);
                ManageListUtil.UpdateMeasurement(gcMyprojectInformation.getId(), mYgcManageLists);
            }
        } else if (isOrganizerValid || isOrganizerHeadValid) {
            addFailedItem(failedItems, contract);
        }
    }

    /**
     * 更新项目
     */
    private void updateExistingContract(GcMyprojectInformation contract, List<Object> failedItems) {

        int result = gcMyprojectInformationService.updateGcMyprojectInformation(contract);
        if (result < 0) {
            addFailedItem(failedItems, contract);
        }
    }

    /**
     * 添加失败项到列表
     */
    private void addFailedItem(List<Object> failedItems, GcMyprojectInformation contract) {
        /*添加失败给客户返回失败项，有项目名的返回项目名，没有的话返回商机id*/
        failedItems.add(contract.getProjectName() != null ? contract.getProjectName() : contract.getBusinessId());
    }

    /**
     * 构建响应结果
     */
    private AjaxResult buildResponse(List<Object> failedItems) {
        if (!failedItems.isEmpty()) {
            String joinedString = StringUtils.join(failedItems, ",");
            return new AjaxResult(500, "部分操作失败", joinedString);
        }
        return new AjaxResult(200, "操作成功", null);
    }

    /**
     * 新增我得项目主表
     * 加密项目
     */
    @PostMapping("/add")
    @ResponseBody
    public static String add(@RequestBody GcMyprojectInformation gcData) {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonData = null;
        String encryptedData = null;
        try {
            jsonData = objectMapper.writeValueAsString(gcData);
            encryptedData = AESUtils.encrypt(jsonData);
            System.out.println("加密后的数据:");
            System.out.println(encryptedData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        访问接口地址+encryptedData
        System.out.println("Original JSON Data: " + jsonData);

        return encryptedData;
    }


    /*获取请求体*/
    public static String getRequestBody(HttpServletRequest request) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        String str = "";
        try {
            br = request.getReader();
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (br != null) {
                try {
                    br.close();
                } catch (IOException eo) {
                    eo.printStackTrace();
                }
            }
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}
